/*
 * Atomic Predicates for Transformers
 * 
 * Copyright (c) 2015 UNIVERSITY OF TEXAS AUSTIN. All rights reserved. Developed
 * by: HONGKUN YANG and SIMON S. LAM http://www.cs.utexas.edu/users/lam/NRL/
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * with the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimers.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimers in the documentation
 * and/or other materials provided with the distribution.
 * 
 * 3. Neither the name of the UNIVERSITY OF TEXAS AUSTIN nor the names of the
 * developers may be used to endorse or promote products derived from this
 * Software without specific prior written permission.
 * 
 * 4. Any report or paper describing results derived from using any part of this
 * Software must cite the following publication of the developers: Hongkun Yang
 * and Simon S. Lam, Scalable Verification of Networks With Packet Transformers
 * Using Atomic Predicates, IEEE/ACM Transactions on Networking, October 2017,
 * Volume 25, No. 5, pages 2900-2915 (first published as IEEE Early Access
 * Article, July 2017, Digital Object Identifier: 10.1109/TNET.2017.2720172).
 * 
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH
 * THE SOFTWARE.
 */
package transformer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;

import common.PositionTuple;

public class IPinIPTunnelCone {

    NetworkCOVE net;
    String root;
    HashSet<String> all_tier1s;

    ArrayList<String> tier1s;
    ArrayList<String> others;

    public IPinIPTunnelCone(String netname, String root, String tier1File)
            throws IOException, ClassNotFoundException {

        String serialized = netname + ".ser";
        if (new File(serialized).isFile()) {
            net = NetworkCOVE.read_object(serialized);
        } else {
            //String edgerouterfile = networkname+"edge";
            net = new NetworkCOVE(netname, null);
            net.save_object();
        }

        this.root = root;

        all_tier1s = new HashSet<String>();
        BufferedReader br = new BufferedReader(new FileReader(new File(tier1File)));
        String line;
        while ((line = br.readLine()) != null) {
            String edge = line.trim();
            if (edge.length() > 0) {
                all_tier1s.add(edge);
            }
        }
        br.close();

        tier1s = new ArrayList<String>();
        others = new ArrayList<String>();

        for (String dname : net.boxes.keySet()) {
            if (((Device) net.boxes.get(dname)).has_valid_nataddr())
                if (all_tier1s.contains(dname)) {
                    tier1s.add(dname);
                } else {
                    if (!dname.equals(root)) {
                        others.add(dname);
                    }
                }
        }

        System.out.println(tier1s.size() + " tier1 ASes in the cone");
        System.out.println(others.size() + " other ASes in the cone");
    }

    /**
     * add tunnels to the network on the fly
     *
     * @param tunnel_num
     */
    public void add_tunnels(int tunnel_num) {
        net.ini_IPinIP();
        net.remove_null_routes();

        int cnt = 0;
        for (int i = 0; i < tier1s.size(); i++) {
            for (int j = 0; j < others.size(); j++) {
                if (cnt >= tunnel_num) {
                    break;
                } else {
                    cnt++;
                    net.add_ipinip_tunnel(root, others.get(j), tier1s.get(i));
                    // print out tunnel specifications
                    System.out.println(root + " " + others.get(j) + " " + tier1s.get(i));
                }
            }
        }

        System.out.println(cnt + " tunnels added");
    }

    /**
     * @param tunnel_num: number of IPinIP tunnels to be added to the network
     * @param tunnel_file: stores all IPinIP tunnels created by create_and_save_tunnels(),
     *                                   add tunnels from the file sequentially
     */
    public boolean add_tunnels(int tunnel_num, String tunnel_file) {
        net.ini_IPinIP();
        net.remove_null_routes();
        
        int cnt = 0;
        BufferedReader br;
        try {
            br = new BufferedReader(new FileReader(new File(tunnel_file)));

            String line = null;
            while ((line = br.readLine()) != null && cnt < tunnel_num) {
                String[] tokens = line.trim().split(" ");
                if(tokens.length != 3) {
                    System.err.print("wrong tunnel spec: " + line);
                    br.close();
                    return false;
                }
                System.out.println("tunnel: " + tokens[0] +","+ tokens[1] +","+ tokens[2] + " added");
                net.add_ipinip_tunnel(tokens[0], tokens[1], tokens[2]);
                cnt ++;    
                System.out.println("tunnel: " + tokens + " added");
            }

            br.close();
        } catch ( IOException e) {
            e.printStackTrace();
        }
        System.out.println(cnt + " IPinIP tunnels are added to the network");
        return true;
    }

    /**
     * create all possible tunnels. Each tunnel has entrance at root AS, and exit at a non tier1 AS,
     * and encapsulates packets destined to a tier1 AS. After generating all tunnels, shuffle them and
     * save them to a file.
     */
    public boolean create_and_save_tunnels() {
        ArrayList<String> all_tunnels = new ArrayList<String>();
        for (int i = 0; i < tier1s.size(); i++) {
            for (int j = 0; j < others.size(); j++) {
                String tunnel = root + " " + others.get(j) + " " + tier1s.get(i);
                all_tunnels.add(tunnel);
            }
        }
        Collections.shuffle(all_tunnels);
        System.out.println(all_tunnels.size() + " IPinIP tunnels created");

        String filename = net.name + "_" + root + "_ipiniptunnels";
        // save them to a file
        try {
            PrintWriter pw = new PrintWriter(new FileWriter(filename));
            for (String t : all_tunnels) {
                pw.write(t + "\n");
            }
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        System.out.println("all ipinip tunnels are saved to " + filename);
        return true;
    }

    public double compute_tree(int tunnel_num, PrintWriter pw) {
        add_tunnels(tunnel_num);
        HashSet<PositionTuple> usedpts = new HashSet<PositionTuple>();
        for (PositionTuple pt : net.getallactiveports()) {
            System.out.println(pt);
            if (pt.getPortName().equals(root)) {
                usedpts.add(pt);
                break;
            }
        }

        System.out.println("Port" + usedpts + " are used for computation");

        return StateTransferI2Run.compute_trees_anynontunnelpkt(net, usedpts, pw);
    }

    public static void test_ipinip(String netname, int tunnelnum)
            throws IOException, ClassNotFoundException {
        IPinIPTunnelCone TC = new IPinIPTunnelCone(netname, netname, "tier1");

        String outputfolder = "ipinipcone_" + TC.root + "/";
        File thedir = new File(outputfolder);
        if (!thedir.exists()) {
            thedir.mkdir();
        }

        PrintWriter pw = new PrintWriter(new File(outputfolder + tunnelnum + "tunnels"));
        TC.compute_tree(tunnelnum, pw);
        pw.close();
    }

    public static void main(String[] args)
            throws IOException, NumberFormatException, ClassNotFoundException {
        //test_ipinip(args[0], Integer.parseInt(args[1]));
        IPinIPTunnelCone iptunnelcone = new IPinIPTunnelCone("52941", "52941", "tier1");
        iptunnelcone.create_and_save_tunnels();
    }

}
